package com.gui;

import com.manage.*;
import com.virtual.Run;
import javax.swing.*;
import java.awt.*;
import java.time.LocalDateTime;
import java.util.List;

public class StudentManagementPanel extends JPanel {
    private Run systemManager;
    private JComboBox<ClassRoom> classSelector;
    private JList<Student> studentList;
    private DefaultListModel<Student> studentListModel;
    private JTextArea recordsArea;
    
    public StudentManagementPanel(Run systemManager) {
        this.systemManager = systemManager;
        initializeUI();
        // 初始化后立即更新列表
        updateClassSelector();
        // 如果有班级，选择第一个班级并更新学生列表
        if (classSelector.getItemCount() > 0) {
            classSelector.setSelectedIndex(0);
            updateStudentList();
        }
    }
    
    private void initializeUI() {
        setLayout(new BorderLayout(10, 10));
        
        // 顶部面板：班级选择
        JPanel topPanel = new JPanel();
        classSelector = new JComboBox<>();
        topPanel.add(new JLabel("选择班级："));
        topPanel.add(classSelector);
        
        // 中间面板：学生列表和记录显示
        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
        
        // 左侧：学生列表
        JPanel leftPanel = new JPanel(new BorderLayout());
        studentListModel = new DefaultListModel<>();
        studentList = new JList<>(studentListModel);
        leftPanel.add(new JLabel("学生列表"), BorderLayout.NORTH);
        leftPanel.add(new JScrollPane(studentList), BorderLayout.CENTER);
        
        // 右侧：记录显示
        JPanel rightPanel = new JPanel(new BorderLayout());
        recordsArea = new JTextArea();
        recordsArea.setEditable(false);
        rightPanel.add(new JLabel("学生记录"), BorderLayout.NORTH);
        rightPanel.add(new JScrollPane(recordsArea), BorderLayout.CENTER);
        
        splitPane.setLeftComponent(leftPanel);
        splitPane.setRightComponent(rightPanel);
        splitPane.setDividerLocation(300);
        
        // 底部面板：按钮
        JPanel buttonPanel = new JPanel();
        JButton addStudentBtn = new JButton("新增学生");
        JButton editStudentBtn = new JButton("编辑学生");
        JButton deleteStudentBtn = new JButton("删除学生");
        JButton addAttendanceBtn = new JButton("记录考勤");
        JButton addAnswerBtn = new JButton("记录答题");
        
        buttonPanel.add(addStudentBtn);
        buttonPanel.add(editStudentBtn);
        buttonPanel.add(deleteStudentBtn);
        buttonPanel.add(addAttendanceBtn);
        buttonPanel.add(addAnswerBtn);
        
        // 添加到主面板
        add(topPanel, BorderLayout.NORTH);
        add(splitPane, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);
        
        // 添加事件监听
        classSelector.addActionListener(e -> {
            updateStudentList();
            recordsArea.setText(""); // 清空记录显示
        });
        studentList.addListSelectionListener(e -> {
            if (!e.getValueIsAdjusting()) {
                updateRecordsDisplay();
            }
        });
        addStudentBtn.addActionListener(e -> showAddStudentDialog());
        editStudentBtn.addActionListener(e -> editSelectedStudent());
        deleteStudentBtn.addActionListener(e -> deleteSelectedStudent());
        addAttendanceBtn.addActionListener(e -> showAddAttendanceDialog());
        addAnswerBtn.addActionListener(e -> showAddAnswerDialog());
        
        // 设置列表选择模式
        studentList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        
        // 在 initializeUI 方法中设置首选大小
        recordsArea.setPreferredSize(new Dimension(400, 300));
        studentList.setPreferredSize(new Dimension(200, 300));
    }
    
    private void updateClassSelector() {
        classSelector.removeAllItems();
        for (ClassRoom classRoom : systemManager.getClasses()) {
            classSelector.addItem(classRoom);
        }
    }
    
    private void updateStudentList() {
        studentListModel.clear();
        ClassRoom selectedClass = (ClassRoom) classSelector.getSelectedItem();
        if (selectedClass != null) {
            for (Student student : selectedClass.getStudents()) {
                studentListModel.addElement(student);
            }
        }
    }
    
    private void updateRecordsDisplay() {
        Student selectedStudent = studentList.getSelectedValue();
        if (selectedStudent != null) {
            StringBuilder sb = new StringBuilder();
            sb.append("学生信息：\n");
            sb.append("姓名：").append(selectedStudent.getName()).append("\n");
            sb.append("学号：").append(selectedStudent.getId()).append("\n\n");
            
            sb.append("考勤记录：\n");
            for (AttendanceRecord record : selectedStudent.getAttendanceRecords()) {
                sb.append("时间：").append(record.getDateTime())
                  .append("，出勤状态：").append(record.isPresent() ? "出勤" : "缺勤")
                  .append("，备注：").append(record.getRemark())
                  .append("\n");
            }
            
            sb.append("\n答题记录：\n");
            for (AnswerRecord record : selectedStudent.getAnswerRecords()) {
                sb.append("时间：").append(record.getDateTime())
                  .append("，题目：").append(record.getQuestion())
                  .append("，答案：").append(record.getAnswer())
                  .append("，得分：").append(record.getScore())
                  .append("\n");
            }
            
            recordsArea.setText(sb.toString());
        } else {
            recordsArea.setText("");
        }
    }
    
    private void showAddStudentDialog() {
        ClassRoom selectedClass = (ClassRoom) classSelector.getSelectedItem();
        if (selectedClass != null) {
            JPanel panel = new JPanel(new GridLayout(2, 2));
            panel.add(new JLabel("学号："));
            JTextField idField = new JTextField();
            panel.add(idField);
            panel.add(new JLabel("姓名："));
            JTextField nameField = new JTextField();
            panel.add(nameField);
            
            int result = JOptionPane.showConfirmDialog(this, panel, 
                "添加新学生", JOptionPane.OK_CANCEL_OPTION);
                
            if (result == JOptionPane.OK_OPTION) {
                String id = idField.getText().trim();
                String name = nameField.getText().trim();
                if (!id.isEmpty() && !name.isEmpty()) {
                    Student newStudent = new Student(id, name);
                    selectedClass.addStudent(newStudent);
                    updateStudentList();
                    studentList.setSelectedValue(newStudent, true);
                }
            }
        } else {
            JOptionPane.showMessageDialog(this, 
                "请先选择一个班级！", 
                "提示", 
                JOptionPane.WARNING_MESSAGE);
        }
    }
    
    private void editSelectedStudent() {
        Student selectedStudent = studentList.getSelectedValue();
        if (selectedStudent != null) {
            JPanel panel = new JPanel(new GridLayout(2, 2));
            panel.add(new JLabel("学号："));
            JTextField idField = new JTextField(selectedStudent.getId());
            panel.add(idField);
            panel.add(new JLabel("姓名："));
            JTextField nameField = new JTextField(selectedStudent.getName());
            panel.add(nameField);
            
            int result = JOptionPane.showConfirmDialog(this, panel, 
                "编辑学生信息", JOptionPane.OK_CANCEL_OPTION);
                
            if (result == JOptionPane.OK_OPTION) {
                String id = idField.getText().trim();
                String name = nameField.getText().trim();
                if (!id.isEmpty() && !name.isEmpty()) {
                    selectedStudent.setId(id);
                    selectedStudent.setName(name);
                    updateStudentList();
                    updateRecordsDisplay();
                }
            }
        }
    }
    
    private void deleteSelectedStudent() {
        Student selectedStudent = studentList.getSelectedValue();
        ClassRoom selectedClass = (ClassRoom) classSelector.getSelectedItem();
        if (selectedStudent != null && selectedClass != null) {
            int confirm = JOptionPane.showConfirmDialog(this, 
                "确定要删除该学生吗？", "确认删除", 
                JOptionPane.YES_NO_OPTION);
            if (confirm == JOptionPane.YES_OPTION) {
                selectedClass.removeStudent(selectedStudent);
                updateStudentList();
                recordsArea.setText("");
            }
        }
    }
    
    private void showAddAttendanceDialog() {
        Student selectedStudent = studentList.getSelectedValue();
        if (selectedStudent != null) {
            JPanel panel = new JPanel(new GridLayout(2, 2));
            panel.add(new JLabel("出勤状态："));
            JCheckBox presentBox = new JCheckBox("出勤");
            panel.add(presentBox);
            panel.add(new JLabel("备注："));
            JTextField remarkField = new JTextField();
            panel.add(remarkField);
            
            int result = JOptionPane.showConfirmDialog(this, panel, 
                "添加考勤记录", JOptionPane.OK_CANCEL_OPTION);
                
            if (result == JOptionPane.OK_OPTION) {
                AttendanceRecord record = new AttendanceRecord(
                    LocalDateTime.now(),
                    presentBox.isSelected(),
                    remarkField.getText().trim()
                );
                selectedStudent.addAttendanceRecord(record);
                updateRecordsDisplay();
            }
        }
    }
    
    private void showAddAnswerDialog() {
        Student selectedStudent = studentList.getSelectedValue();
        if (selectedStudent != null) {
            JPanel panel = new JPanel(new GridLayout(4, 2));
            panel.add(new JLabel("题目："));
            JTextField questionField = new JTextField();
            panel.add(questionField);
            panel.add(new JLabel("答案："));
            JTextField answerField = new JTextField();
            panel.add(answerField);
            panel.add(new JLabel("是否正确："));
            JCheckBox correctBox = new JCheckBox();
            panel.add(correctBox);
            panel.add(new JLabel("得分："));
            JTextField scoreField = new JTextField();
            panel.add(scoreField);
            
            int result = JOptionPane.showConfirmDialog(this, panel, 
                "添加答题记录", JOptionPane.OK_CANCEL_OPTION);
                
            if (result == JOptionPane.OK_OPTION) {
                try {
                    double score = Double.parseDouble(scoreField.getText().trim());
                    AnswerRecord record = new AnswerRecord(
                        LocalDateTime.now(),
                        correctBox.isSelected(),
                        score,
                        questionField.getText().trim(),
                        answerField.getText().trim()
                    );
                    selectedStudent.addAnswerRecord(record);
                    updateRecordsDisplay();
                } catch (NumberFormatException e) {
                    JOptionPane.showMessageDialog(this, 
                        "请入有效的分数！", "输入错误", 
                        JOptionPane.ERROR_MESSAGE);
                }
            }
        }
    }

    @Override
    public void setVisible(boolean visible) {
        super.setVisible(visible);
        if (visible) {
            // 每次面板变为可见时更新数据
            updateClassSelector();
            updateStudentList();
            recordsArea.setText("");
        }
    }
} 